package com.example.administrator.smartdevice.fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.administrator.smartdevice.R;
import com.example.administrator.smartdevice.activity.DeviceActivity;
import com.example.administrator.smartdevice.adapter.AskListAdapter;
import com.example.administrator.smartdevice.base.BaseFragment;
import com.example.administrator.smartdevice.event.AskListEvent;
import com.example.administrator.smartdevice.event.MessageEvent;
import com.example.administrator.smartdevice.net.HttpUtils;
import com.example.administrator.smartdevice.utils.AgentConstants;
import com.example.administrator.smartdevice.utils.AgentSharedPreferences;
import com.example.administrator.smartdevice.utils.AgentUtils;
import com.example.administrator.smartdevice.utils.AppApplication;
import com.example.administrator.smartdevice.utils.FileUtil;
import com.example.administrator.smartdevice.utils.ServerConstants;
import com.example.administrator.smartdevice.utils.StringUtils;
import com.example.administrator.smartdevice.utils.UUIDUtil;
import com.example.administrator.smartdevice.widget.AppendDialog;
import com.example.administrator.smartdevice.widget.CustomTipDialog;
import com.hhc.netty.DeviceModel;
import com.hhc.netty.NettyClient;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

/**
 * Created by Administrator on 2018/4/30.
 */

public class AskListFragment extends BaseFragment {
    @BindView(R.id.fragment_device_list)
    protected RecyclerView fragment_device_list;
    @BindView(R.id.fragment_message_refreshLayout)
    protected SmartRefreshLayout fragment_message_refreshLayout;
    protected List<MessageEvent> data = new ArrayList();
    private AskListAdapter askListAdapter;
    private String masterId;
    private String applianceId;
    private String applianceType;
    private String photoPath;
    private int mPosition = 0;

    public static AskListFragment newInstance() {
        return new AskListFragment();
    }

    @Override
    protected void initData(View view, Bundle savedInstanceState) {
        initView();
        initRefresh();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_device_list;
    }

    @Override
    protected void onFailure(int requestCode, Object object) {

    }

    @Override
    protected void onSuccess(int requestCode, Object object) {
        stopTipDialog();
        fragment_message_refreshLayout.finishRefresh();
        if (object != null) {
            switch (requestCode) {
                case 1001:
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        String newUrl = (String) HttpUtils.getData(object, String.class);
                        //更新到appliancePic
                        addAppliance(newUrl);
                    }
                    break;
                case 1002:
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        showToast(HttpUtils.getResultMessage(object));
                        DeviceModel deviceModel = new DeviceModel();
                        //基本项：device_id和appliance_id
                        deviceModel.setDeviceId(AgentSharedPreferences.getMemberInfo(AppApplication.getContext()).getMemberDeviceId());
                        deviceModel.setApplianceId(askListAdapter.getDataList().get(mPosition).getApplianceId());
                        //家电上线状态:上线
                        deviceModel.setOnlineStatus("10");
                        //家电开关状态：关
                        deviceModel.setStatus("20");
                        NettyClient.getInstance().deviceOnline(deviceModel);

                        askListAdapter.getDataList().remove(mPosition);
                        askListAdapter.notifyItemRemoved(mPosition);//推荐用这个
                        if (mPosition != (askListAdapter.getDataList().size())) { // 如果移除的是最后一个，忽略 注意：这里的mDataAdapter.getDataList()不需要-1，因为上面已经-1了
                            askListAdapter.notifyItemRangeChanged(mPosition, askListAdapter.getDataList().size() - mPosition);
                        }


                    } else {
                        showToast(HttpUtils.getResultMessage(object));
                    }
                    break;
                default:
                    break;
            }
        }
    }

    protected void initView() {
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(mBaseActivity, LinearLayoutManager.VERTICAL, false);
        fragment_device_list.setLayoutManager(mLayoutManager);
        data = NettyClient.getInstance().getAskList();
        askListAdapter = new AskListAdapter(mBaseActivity, data);
        fragment_device_list.setAdapter(askListAdapter);
        askListAdapter.setOnItemClickListener(new AskListAdapter.OnItemClickListener() {
            @Override
            public void onClick(final int position) {
                final AppendDialog appendDialog = new AppendDialog(mBaseActivity);
                appendDialog.setOnAddClickListener(new AppendDialog.OnAddClickListener() {
                    @Override
                    public void onAddClick(String password) {
                        if (password.equals(NettyClient.getInstance().getAskList().get(position).getParams().trim())) {
                            //先生成图片
                            mPosition = position;
                            masterId = UUIDUtil.get36UUID();
                            applianceId = NettyClient.getInstance().getAskList().get(position).getApplianceId();
                            applianceType = NettyClient.getInstance().getAskList().get(position).getApplianceType();
                            CreateQRCodeTask e = new CreateQRCodeTask((DeviceActivity) getActivity(), getJsonString(masterId));
                            e.execute();
                            appendDialog.dismiss();
                        } else {
                            showToast("匹配密码错误");
                        }
                    }
                });
                appendDialog.show();
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AskListEvent askListEvent) {
        Log.d("hhc", "onEventMainThread: 123");
        askListAdapter.notifyDataSetChanged();
    }

    public String getJsonString(String masterId) {
        return "{\"masterId\":\"" + masterId + "\"}";
    }

    //上传图片
    public void uploadAppliancePic(File file) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileName", masterId);
        jsonObject.put("file", FileUtil.encodeBase64File(file));
        jsonObject.put("suffix", "jpg");
        Log.d("hhc", "uploadAppliancePic: " + jsonObject);
        HttpUtils.post(mBaseActivity, 1001, ServerConstants.UPLOAD_AVATAR, jsonObject.toString(), this);
    }

    private void addAppliance(String url) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberId", AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone());
        jsonObject.put("masterId", masterId);
        jsonObject.put("applianceId", applianceId);
        jsonObject.put("applianceType", applianceType);
        jsonObject.put("applianceName", StringUtils.getApplianceType(applianceType));
        jsonObject.put("appliancePic", url);
        jsonObject.put("sceneMasterId", "");
        HttpUtils.post(mBaseActivity, 1002, ServerConstants.ADD_APPLIANCE, jsonObject.toString(), this);
        startTipDialog(CustomTipDialog.ICON_TYPE_LOADING, getString(R.string.common_adding), true);
    }

    private void requestSdCardPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasWriteSdPermission = getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasWriteSdPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                }, 2000);
            } else {
                uploadAppliancePic(new File(photoPath));
            }
        } else {
            uploadAppliancePic(new File(photoPath));
        }
    }

    public void initRefresh() {
        fragment_message_refreshLayout.setEnableLoadmore(false);
        fragment_message_refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                askListAdapter.notifyDataSetChanged();
                fragment_message_refreshLayout.finishRefresh();
            }
        });
    }

    class CreateQRCodeTask extends AsyncTask<Void, Void, Bitmap> {
        // 弱引用是允许被gc回收的;
        private final WeakReference<DeviceActivity> mActivity;
        public String mContent;

        CreateQRCodeTask(DeviceActivity mActivity, String content) {
            this.mActivity = new WeakReference<>(mActivity);
            this.mContent = content;
        }

        @Override
        protected Bitmap doInBackground(Void... params) {
            Bitmap logoBitmap = BitmapFactory.decodeResource(mActivity.get().getResources(), R.mipmap.icon_logo1);
            return QRCodeEncoder.syncEncodeQRCode(mContent, BGAQRCodeUtil.dp2px(mActivity.get(), 200), Color.BLACK, Color.WHITE, logoBitmap);

        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            DeviceActivity activity = mActivity.get();
            if (activity == null
                    || activity.isFinishing()) {
                // activity没了,就结束可以了
                return;
            }
            if (bitmap != null) {
                //成功创建，上传到服务器
                photoPath = AgentUtils.getImageCachePath() + "/" + masterId + ".jpg";
                FileUtil.saveBitmapFile(bitmap, photoPath);
                Log.d("hhc", "onPostExecute: " + photoPath);
                requestSdCardPermission();
            } else {
                Toast.makeText(mActivity.get(), "生成带logo的英文二维码失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
